import React, {useEffect, useRef, useState} from 'react';
import {Content} from "antd/es/layout/layout";
import Search from "antd/es/input/Search";
import {Image, List, message, notification, Spin} from "antd";
import axios from "axios";
import {SafetyCertificateTwoTone} from "@ant-design/icons";

const GET_IMAGE_URL = "https://wenxin.baidu.com/younger/portal/api/rest/1.0/ernievilg/v1/txt2img";
const AK = "...";
const SK = "...";
const GET_ACCESS_TOKEN_URL = "https://wenxin.baidu.com/younger/portal/api/oauth/token" +
  "?grant_type=client_credentials&client_id=" + AK + "&client_secret=" + SK;
const GET_IMAGE_URLS_URL = "https://wenxin.baidu.com/younger/portal/api/rest/1.0/ernievilg/v1/getImg";

interface StyleProps {
  styles: React.CSSProperties
}

const MyContent = (props: StyleProps) => {
  const [messageApi, contextHolder] = message.useMessage();
  const [api, contextHolderSuccess] = notification.useNotification();
  const form = useRef({
    style: '油画',
    text: '',
    access_token: ''
  })
  const urls = useRef<string[]>([]);
  const [loading, setLoading] = useState(false);

  /*根据ak、sk获取access_token*/
  const getAccessToken = () => {
    axios.post(GET_ACCESS_TOKEN_URL, null, {
        headers: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
      }
    ).then(async (res) => {
      if (res.data.msg === "success") {
        messageApi.open({
          type: "success",
          content: "获取access_token成功！",
          duration: 2
        })
        form.current.access_token = res.data.data
      }
    })
  }

  /*根据 access_token 请求生成图片*/
  const getImage = async () => {
    await axios.post(GET_IMAGE_URL, form.current, {
      headers: {
        "Content-Type": "application/x-www-form-urlencoded"
      }
    }).then((res) => {
      if (res.data.msg === "success" && res.data.data !== undefined) {
        let taskId = res.data.data.taskId;
        let accessToken = form.current.access_token;
        api.info({
          icon: <SafetyCertificateTwoTone twoToneColor="#3cd768"/>,
          message: "图片生成成功",
          description: "图片生成成功！请稍作等待...",
          duration: 3,
          placement: "topRight"
        })
        setLoading(false);
        let intervalId = setInterval(() => {
          /*获取图片urls*/
          getImageUrls({
            taskId: taskId,
            access_token: accessToken
          })
          if (urls.current.length !== 0) {
            clearInterval(intervalId);
            setLoading(false);
            return;
          }
          return;
        }, 2500)
      }
    })
  }

  /*获取生成的url*/
  const getImageUrls = (imageForm: any) => {
    axios.post(GET_IMAGE_URLS_URL, imageForm).then((res) => {
      if (res.data.msg === "success") {
        const imgUrls = res.data.data.imgUrls;
        urls.current = imgUrls.map((item: { image: string; }) => item.image);
      }
    })
  }

  const onGenerate = async (value: string) => {
    form.current.text = value
    urls.current = []
    await getImage()
    setLoading(true)
  }

  useEffect(() => {
    getAccessToken()
  }, [])

  return (
    <>
      {contextHolder} {contextHolderSuccess}
      <Content style={props.styles}>
        <Search
          onSearch={onGenerate}
          placeholder="请输入描述"
          allowClear
          enterButton="生成"
          size="large"
          style={{width: '50%', margin: '10px'}}
        />
        <Spin spinning={loading} tip="正在请求获取生成的图片，请耐心等待...">
          <Image.PreviewGroup>
            <List
              dataSource={urls.current}
              grid={{gutter: 1, column: 4}}
              renderItem={(item) => (
                <List.Item>
                  <Image src={item}/>
                </List.Item>
              )}
            >
            </List>
          </Image.PreviewGroup>
        </Spin>
      </Content>
    </>
  );
};

MyContent.propTypes = {};

export default MyContent;
